import axios, {AxiosError, AxiosInstance, AxiosResponse, CancelTokenSource} from 'axios';
import {FilterCondition} from "@/components/crud/types";
import {debounce} from "lodash-es";
import router from "@/router";
import {STORAGE_KEYS} from "@/constants/storageKeys";

// 定义 Strapi 响应数据的通用结构
export interface StrapiResponse<T> {
    data: T;
    meta?: Record<string, any>;
    error?:any
    total?: number; // 用于分页的总记录数
}



interface SortCondition {
    field: string;
    order: 'asc' | 'desc';
}

// 创建一个 axios 实例
const api: AxiosInstance = axios.create({
    baseURL: import.meta.env.VITE_STRAPI_API_URL || 'http://localhost:1337/api', // Strapi API 的基础 URL
    headers: {
        'Content-Type': 'application/json',
    },
});
// 处理未登录情况
api.interceptors.response.use(
    (response) => response,
    (error) => {
        const { response } = error;
        // 处理401错误
        if (response && response.status === 401) {
            handleLogout(); // 调用防抖处理的登出函数
        }
        return Promise.reject(error);
    }
);
// 创建防抖处理的登出函数
const handleLogout = debounce(() => {
    // 清除存储的认证令牌
    localStorage.removeItem(STORAGE_KEYS.STRAPI_JWT);
    // 跳转到登录页面，并记录当前路径用于登录后重定向
    router.push({
        name: 'login',
        query: { redirect: router.currentRoute.value.fullPath }
    });
}, 500); // 500ms防抖延迟

// 设置认证令牌
export const setAuthToken = (token: string | null): void => {
    if (token) {
        api.defaults.headers.common['Authorization'] = `Bearer ${token}`;
    } else {
        delete api.defaults.headers.common['Authorization'];
    }
};

// 获取所有条目，增加分页参数和查询条件
export const getEntries = async <T>(
    contentType: string,
    page: number = 1, // 默认页码为 1
    pageSize: number = 25, // 默认每页 25 条记录
    filters: FilterCondition[] , // 过滤条件
    sorts: SortCondition[] = [] , // 排序条件
    fields: string[] = [], // 选择的字段
    source?: CancelTokenSource
): Promise<StrapiResponse<T>> => {
    try {
        // 构建查询参数
        const params: Record<string, any> = {
            'pagination[page]': page,
            'pagination[pageSize]': pageSize
        };

        // 添加过滤条件
        if (filters.length > 0) {
            filters.forEach(({ field, operator, value }) => {
                const filterKey = `filters[${field}][${operator}]`;
                if (Array.isArray(value)) {
                    params[filterKey] = value.join(',');
                } else {
                    params[filterKey] = value;
                }
            });
        }

        // 添加排序条件
        if (sorts.length > 0) {
            const sortStrings = sorts.map(sort => `${sort.field}:${sort.order}`);
            params['sort'] = sortStrings.join(',');
        }

        // 添加字段选择条件
        if (fields.length > 0) {
            params['populate'] = fields.join(',');
        }

        // 构建包含分页参数和查询条件的 URL
        const response: AxiosResponse<StrapiResponse<T>> = await api.get(`/${contentType}`, {
            params,
            cancelToken: source ? source.token : undefined
        });
        return response.data;
    } catch (error: any) {
        if (error.status === 401 || error.status === 403) {
            console.error('未登录');
        }
        throw error;
    }
};

// 获取单个条目
export const getEntry = async <T>(contentType: string, id: string | number): Promise<StrapiResponse<T>> => {
    try {
        const response: AxiosResponse<StrapiResponse<T>> = await api.get(`/${contentType}/${id}`);
        return response.data;
    } catch (error) {
        console.error('获取单个条目失败:', error);
        throw error;
    }
};

// 创建新条目
export const createEntry = async <T>(url: string, data: any): Promise<StrapiResponse<T>> => {
    try {
        const response: AxiosResponse<StrapiResponse<T>> = await api.post(`/${url}`, {data: data});
        return response.data;
    } catch (error:any) {
        throw error.response.data.error;
    }
};

// 更新条目
export const updateEntry = async <T>(contentType: string, id: string | number, data: any): Promise<StrapiResponse<T>> => {
    try {
        const response: AxiosResponse<StrapiResponse<T>> = await api.put(`/${contentType}/${id}`, {data});
        return response.data;
    } catch (error) {
        console.error('更新条目失败:', error);
        throw error;
    }
};

// 删除条目
export const deleteEntry = async <T>(contentType: string, id: string | number): Promise<StrapiResponse<T>> => {
    try {
        const response: AxiosResponse<StrapiResponse<T>> = await api.delete(`/${contentType}/${id}`);
        return response.data;
    } catch (error) {

        console.error('删除条目失败:', error);
        throw error;
    }
};

const token = localStorage.getItem(STORAGE_KEYS.STRAPI_JWT);
setAuthToken(token);
export default api;
